package handler

import (
	"context"
	"easy-note/models"
	note "easy-note/note/kitex_gen/note"
	"easy-note/note/repo"
)

// NoteImpl implements the last service interface defined in the IDL.
type NoteImpl struct {
	Repo repo.NoteRepo
}

// InsertNote implements the NoteImpl interface.
func (s *NoteImpl) InsertNote(ctx context.Context, req *note.ReqInsertNote) (resp *note.ResInsertNote, err error) {
	isSuccess, err := s.Repo.InsertNote(&models.NoteInfo{
		Name:   req.GetName(),
		Note:   req.GetNote(),
		UserId: int(req.GetUserId()),
	})
	if err != nil {
		return &note.ResInsertNote{IsSuccess: false}, err
	}
	return &note.ResInsertNote{IsSuccess: isSuccess}, nil
}

// DeleteNote implements the NoteImpl interface.
func (s *NoteImpl) DeleteNote(ctx context.Context, req *note.ReqDeleteNote) (resp *note.ResDeleteNote, err error) {
	isSuccess, err := s.Repo.DeleteNote(int(req.GetId()), int(req.GetUserId()))
	if err != nil {
		return &note.ResDeleteNote{IsSuccess: false}, err
	}
	return &note.ResDeleteNote{IsSuccess: isSuccess}, nil
}

// UpdateNote implements the NoteImpl interface.
func (s *NoteImpl) UpdateNote(ctx context.Context, req *note.ReqUpdateNote) (resp *note.ResUpdateNote, err error) {
	isSuccess, err := s.Repo.UpdateNote(int(req.GetId()), int(req.GetUserId()), req.GetName(), req.GetNote())
	if err != nil {
		return &note.ResUpdateNote{IsSuccess: false}, err
	}
	return &note.ResUpdateNote{IsSuccess: isSuccess}, nil
}

// GetNoteById implements the NoteImpl interface.
func (s *NoteImpl) GetNoteById(ctx context.Context, req *note.ReqGetNoteById) (resp *note.ResGetNoteById, err error) {
	noteRepo, err := s.Repo.GetNoteById(int(req.GetId()), int(req.GetUserId()))
	if err != nil {
		return nil, err
	}
	return &note.ResGetNoteById{
		Name:      noteRepo.Name,
		Note:      noteRepo.Note,
		UserId:    int32(noteRepo.UserId),
		CreatedAt: noteRepo.CreatedAt.String(),
		UpdatedAt: noteRepo.UpdatedAt.String(),
		Id:        int32(noteRepo.Id),
	}, nil
}

// ListNote implements the NoteImpl interface.
func (s *NoteImpl) ListNote(ctx context.Context, req *note.ReqListNote) (resp *note.ResListNote, err error) {
	var total = req.GetTotal()
	notes, err := s.Repo.ListNote(int(req.GetPage()), int(req.GetSize()), int(req.GetUserId()), &total)
	if err != nil {
		resp.Notes = nil
		return &note.ResListNote{Notes: nil}, err
	}
	var newNotes []*note.ResGetNoteById
	for _, item := range notes {
		newNotes = append(newNotes, &note.ResGetNoteById{
			Name:      item.Name,
			Note:      item.Note,
			UserId:    int32(item.UserId),
			CreatedAt: item.CreatedAt.String(),
			UpdatedAt: item.UpdatedAt.String(),
			Id:        int32(item.Id),
		})
	}
	return &note.ResListNote{Notes: newNotes, Total: total}, nil
}
